<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2020/2/20
 * Time: 16:46
 */

namespace app\admin\controller;


use think\Db;
use think\Request;
class Plan extends Base
{
    /**
     * 用户列表
     * @return mixed|\think\response\Json
     */
    public function index(){
        if(request()->isAjax()){
            $where = [
//                'pa_id' => ['>',0],
                'p_status' => ['<>',3]
            ];
            if(session('groupid') == 2){
                $where['p_piano'] = session('piano');
            }
            $keyword = input('keyword');
            $user_school = input('user_school');
            if(isset($keyword) && $keyword != ''){
                $where['p_name|user_username'] = ['like', '%' . $keyword . '%'];
            }
            //琴行
            if(isset($user_school) && $user_school != "")
            {
                $where['p_piano'] = $user_school;
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'p.*,user_username,user_phone,pa_name';
            $count = Db::table('up_plan')->alias('p')
                ->join('up_piano pi','p.p_piano=pi.pa_id','LEFT')
                ->join('up_u_user u','p.p_student=u.user_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_plan')->alias('p')
                ->join('up_piano pi','p.p_piano=pi.pa_id','LEFT')
                ->join('up_u_user u','p.p_student=u.user_id','LEFT')
                ->where($where)
                ->page($NowPage,$limits)
                ->order('p_time desc')
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $panio = Db::table('up_piano')
            ->select();
        if(session('groupid') == 2){
            $panio = Db::table('up_piano')
                ->where('pa_id',session('piano'))
                ->select();
        }
        $this->assign([
            'panio' => $panio,
        ]);
        return $this->fetch();
    }
    
    /**
     * 冻结
     * @return \think\response\Json
     */
    public function down(){
        $user_id = input('id');
        Db::startTrans();
        try {
            Db::table('up_plan')->where('p_id', $user_id)->setField('p_status', 2);
            Db::table('up_plan_info')->where('plan_p_id', $user_id)->setField('plan_online', 2);
            Db::table('up_plan_practice')->where('pra_p_id', $user_id)->setField('pra_online', 2);
            Db::commit();
            return json(['code' => 200, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 启用
     * @return \think\response\Json
     */
    public function up(){
        $user_id = input('id');
        $p_student = Db::table('up_plan')->where('p_id', $user_id)->value('p_student');
        $have = Db::table('up_plan')
            ->where('p_student', $p_student)
            ->where('p_status', 1)
            ->find();
        if($have){
            return json(['code' => 100, 'msg' => '已经有上架的课程了']);
        }
        Db::startTrans();
        try {
            Db::table('up_plan')->where('p_id', $user_id)->setField('p_status', 1);
            Db::table('up_plan_info')->where('plan_p_id', $user_id)->setField('plan_online', 1);
            Db::table('up_plan_practice')->where('pra_p_id', $user_id)->setField('pra_online', 1);
            Db::commit();
            return json(['code' => 200, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    /**
     * 删除
     * @return \think\response\Json
     */
    public function deluser(){
        $user_id = input('id');
        Db::startTrans();
        try {
            Db::table('up_plan')->where('p_id', $user_id)->setField('p_status', 3);
            Db::table('up_plan_info')->where('plan_p_id', $user_id)->setField('plan_online', 3);
            Db::table('up_plan_practice')->where('pra_p_id', $user_id)->setField('pra_online', 3);
            Db::commit();
            return json(['code' => 200, 'msg' => '操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 添加
     * @return mixed
     */
    public function addList(){
        if(Request::instance()->isPost()){
            $l_title = input('p_name');
            $l_status = input('p_status');
            $l_piano = input('p_piano');
            $l_student = input('p_student');
            $p_start = input('p_start');
            $p_end = input('p_end');
            if($p_end <= $p_start){
                return json(['code' => 100, 'msg' => '结束日期不能小于开始日期']);
            }
            $insert = [
                'p_name' => $l_title,
                'p_status' => $l_status,
                'p_piano' => $l_piano,
                'p_student' => $l_student,
                'p_start' => $p_start,
                'p_end' => $p_end,
                'p_admin' => session('username'),
                'p_time' => date('Y-m-d H:i:s')
            ];
            if($l_status == 1){
                $have = Db::table('up_plan')
                    ->where('p_student', $l_student)
                    ->where('p_status', 1)
                    ->find();
                if($have){
                    return json(['code' => 100, 'msg' => '已经有上架的课程了']);
                }
            }
            Db::startTrans();
            try {
                $res = Db::table('up_plan')->insertGetId($insert);
                $allpras = [];
                $days = (strtotime($p_end) - strtotime($p_start))/3600/24;
                for($i=0;$i<=$days;$i++){
                    $pradate = date("Y-m-d",strtotime("$p_start +$i days"));
                    $allpras[] = [
                        'pra_p_id' => $res,
                        'pra_name' => '自由练习',
                        'pra_date' => $pradate,
                        'pra_student' => $l_student,
                        'pra_online' => $l_status,
                        'pra_admin' => session('username'),
                        'pra_time' => date('Y-m-d H:i:s')
                    ];
                }
                Db::table('up_plan_practice')->insertAll($allpras);
                Db::commit();
                return json(['code' => 200, 'msg' => '操作成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 100, 'msg' => '操作失败']);
            }
        }
        $panio = Db::table('up_piano')
            ->order('pa_id desc')
            ->select();
        if(session('groupid') == 2){
            $panio = Db::table('up_piano')
                ->where('pa_id',session('piano'))
                ->select();
        }
        $this->assign('panio', $panio);
        return $this->fetch('plan/addlist');
    }
    /**
     * 编辑
     * @return mixed
     */
    public function memberEdit(){
        $p_id = input('p_id');
        if(Request::instance()->isPost()){
            $l_title = input('p_name');
            $l_status = input('p_status');
            $update = [
                'p_name' => $l_title,
                'p_status' => $l_status,
                'p_admin' => session('username'),
                'p_time' => date('Y-m-d H:i:s')
            ];
            $p_data = Db::table('up_plan')->where('p_id', $p_id)->field('p_student,p_status')->find();
            if($l_status == 1){
                $p_student = $p_data['p_student'];
                $have = Db::table('up_plan')
                    ->where('p_student', $p_student)
                    ->where('p_status', 1)
                    ->where('p_id', '<>',$p_id)
                    ->find();
                if($have){
                    return json(['code' => 100, 'msg' => '已经有上架的课程了']);
                }
            }
            //如果提交的这个状态跟以前的不一样，那此课程下的计划和训练都要变化
            if($p_data['p_status'] != $l_status){
                Db::table('up_plan_info')->where('plan_p_id', $p_id)->setField('plan_online', $l_status);
                Db::table('up_plan_practice')->where('pra_p_id', $p_id)->setField('pra_online', $l_status);
            }
            $res = Db::table('up_plan')->where('p_id',$p_id)->update($update);
            if($res){
                return json(['code' => 200, 'msg' => '成功']);
            }else{
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $info = Db::table('up_plan')->alias('p')
            ->join('up_piano pi','p.p_piano=pi.pa_id','LEFT')
            ->join('up_u_user u','p.p_student=u.user_id','LEFT')
            ->where('p_id', $p_id)
            ->find();
        $this->assign('info', $info);
        $this->assign('p_id', $p_id);
        return $this->fetch('plan/listedit');
    }
//------------------------------------计划-----------------------------------------------------------------------
//------------------------------------计划-----------------------------------------------------------------------
//------------------------------------计划-----------------------------------------------------------------------
    /**
     * 计划列表
     * @return mixed|\think\response\Json
     */
    public function planinfo(){
        if(request()->isAjax()){
            $p_id = input('p_id');
            $where = [
                'plan_p_id' => $p_id,
                'plan_online' => ['<>',3]
            ];
            $keyword = input('keyword');
            if(isset($keyword) && $keyword != ''){
                $where['plan_number'] = ['like', '%' . $keyword . '%'];
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $field = 'p.*,user_username,user_phone';
            $count = Db::table('up_plan_info')->alias('p')
                ->join('up_u_user u','p.plan_teacher=u.user_id','LEFT')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_plan_info')->alias('p')
                ->join('up_u_user u','p.plan_teacher=u.user_id','LEFT')
                ->where($where)
                ->page($NowPage,$limits)
                ->order('plan_online asc,plan_sort asc,plan_time desc')
                ->field($field)
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $p_id = input('p_id');
        $info = Db::table('up_plan')->alias('p')
            ->join('up_piano pi','p.p_piano=pi.pa_id','LEFT')
            ->join('up_u_user u','p.p_student=u.user_id','LEFT')
            ->where('p_id', $p_id)
            ->field('pa_name,user_username')
            ->find();
        $this->assign([
            'p_id' => $p_id,
            'info' => $info,
        ]);
        return $this->fetch('plan/planinfo');
    }
    /**
     * 添加计划
     * @return mixed
     */
    public function addPlanInfo(){
        $p_id = input('p_id');
        if(Request::instance()->isPost()){

            $pdata = Db::table('up_plan')
                ->where('p_id', $p_id)
                ->field('p_piano,p_student,p_status')
                ->find();
            if(!$pdata || empty($p_id)){
                return json(['code' => 100, 'msg' => '参数有误，请返回重试']);
            }
            if($pdata['p_status'] != 1){
                return json(['code' => 100, 'msg' => '此课程计划所属课程已下架，不能添加']);
            }
            $today = date('Y-m-d H:i:s');
            $plan_start_time = input('plan_start_time');
            $plan_minus = input('plan_minus');
            if($plan_start_time <= $today){
                return json(['code' => 100, 'msg' => '上课开始时间不能小于当前时间']);
            }
            if($plan_minus <= 0){
                return json(['code' => 100, 'msg' => '上课时长不能少于0']);
            }
            $plan_end_time = date("Y-m-d H:i:s",(strtotime($plan_start_time) + 60*$plan_minus));
            $insert = [
                'plan_p_id' => $p_id,
                'plan_number' => time() . $pdata['p_student'],
                'plan_typename' => input('plan_typename'),
                'plan_teacher' => input('plan_teacher'),
                'plan_student' => $pdata['p_student'],
                'plan_address' => input('address'),
                'plan_way' => input('plan_way'),
                'plan_lat' => input('lat'),
                'plan_lon' => input('lon'),
                'plan_start_time' => $plan_start_time,
                'plan_minus' => $plan_minus,
                'plan_end_time' => $plan_end_time,
                'plan_list' => input('plan_list'),
                'plan_type' => input('plan_type'),
                'plan_sort' => (int)input('plan_sort'),
                'plan_online' => input('plan_online'),

                'plan_admin' => session('username'),
                'plan_time' => $today
            ];
            if($insert['plan_sort'] < 0){
                return json(['code' => 100, 'msg' => '排序值不能低于0']);
            }
            $res = Db::table('up_plan_info')->insertGetId($insert);
            if($res){
                try{
                    $con = '您有新的课程计划，编号：' . $insert['plan_number'] . '，名字：' . $insert['plan_typename'];
                    $nid = allInNotice('您有新的课程计划',$con,6,$insert['plan_student'],$res);
                    $this->Jpush(1, $insert['plan_student'], '您有新的课程计划', ['type'=>6,'nid'=>$nid]);
                }catch(\Exception $e){

                }
                return json(['code' => 200, 'msg' => '成功']);
            }else{
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $where = [
            'user_status' => 1,
            'user_type' => 2
        ];
        if(session('groupid') == 2){
            $where['user_piano'] = ['like','%' . session('piano') . '%'];
        }
        $teachers = Db::table('up_u_user')
            ->where($where)
            ->field('user_id,user_username,user_phone')
            ->select();
        $this->assign('p_id', $p_id);
        $this->assign('teachers', $teachers);
        return $this->fetch('plan/addplaninfo');
    }
    /**
     * 编辑计划
     * @return mixed
     */
    public function planInfoEdit(){
        $plan_id = input('plan_id');
        $info = Db::table('up_plan_info')->where('plan_id', $plan_id)->find();
        $p_id = $info['plan_p_id'];
        if(Request::instance()->isPost()){
            $today = date('Y-m-d H:i:s');
            $plan_start_time = input('plan_start_time');
            $plan_minus = input('plan_minus');
            if($plan_start_time <= $today){
                return json(['code' => 100, 'msg' => '上课开始时间不能小于当前时间']);
            }
            if($plan_minus <= 0){
                return json(['code' => 100, 'msg' => '上课时长不能少于0']);
            }
            $plan_end_time = date("Y-m-d H:i:s",(strtotime($plan_start_time) + 60 * $plan_minus));
            $insert = [
                'plan_p_id' => $p_id,
                'plan_typename' => input('plan_typename'),
                'plan_teacher' => input('plan_teacher'),
                'plan_address' => input('address'),
                'plan_way' => input('plan_way'),
                'plan_lat' => input('lat'),
                'plan_lon' => input('lon'),
                'plan_start_time' => $plan_start_time,
                'plan_minus' => $plan_minus,
                'plan_end_time' => $plan_end_time,
                'plan_list' => input('plan_list'),
                'plan_type' => input('plan_type'),
                'plan_sort' => (int)input('plan_sort'),
                'plan_online' => input('plan_online'),

                'plan_admin' => session('username'),
                'plan_time' => $today
            ];
            if($insert['plan_sort'] < 0){
                return json(['code' => 100, 'msg' => '排序值不能低于0']);
            }
            $res = Db::table('up_plan_info')->where('plan_id',$plan_id)->update($insert);
            if($res){
                try{
                    $con = '您的课程计划更新了，编号：' . $info['plan_number'] . '，名字：' . $insert['plan_typename'];
                    $nid = allInNotice('您的课程计划更新了',$con,6,$info['plan_student'],$plan_id);
                    $this->Jpush(1, $info['plan_student'], '您的课程计划更新了', ['type'=>6,'nid'=>$nid]);
                }catch(\Exception $e){

                }
                return json(['code' => 200, 'msg' => '成功']);
            }else{
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $where = [
            'user_status' => 1,
            'user_type' => 2
        ];
        if(session('groupid') == 2){
            $where['user_piano'] = ['like','%' . session('piano') . '%'];
        }
        $teachers = Db::table('up_u_user')
            ->where($where)
            ->field('user_id,user_username,user_phone')
            ->select();
        $this->assign('p_id', $p_id);
        $this->assign('plan_id', $plan_id);
        $this->assign('info', $info);
        $this->assign('teachers', $teachers);
        return $this->fetch('plan/editplaninfo');
    }
    /**
     * 计划详情
     * @return mixed
     */
    public function planinfo_details(){
        $plan_id = input('plan_id');
        $info = Db::table('up_plan_info')->alias('p')
            ->join('up_u_user u','p.plan_teacher=u.user_id','LEFT')
            ->where('plan_id', $plan_id)
            ->field('p.*,user_id,user_username,user_phone')
            ->find();
        $p_id = $info['plan_p_id'];
        $this->assign('info', $info);
        $p_info = Db::table('up_plan')->alias('p')
            ->join('up_piano pi','p.p_piano=pi.pa_id','LEFT')
            ->join('up_u_user u','p.p_student=u.user_id','LEFT')
            ->where('p_id', $p_id)
            ->field('pa_name,user_username')
            ->find();
        $this->assign('p_info', $p_info);
        return $this->fetch('plan/planinfo_detail');
    }
    /**
     * 计划上架
     * @return \think\response\Json
     */
    public function planup(){
        $user_id = input('id');
        $p_id = Db::table('up_plan_info')->where('plan_id', $user_id)->value('plan_p_id');
        $pdata = Db::table('up_plan')
            ->where('p_id', $p_id)
            ->field('p_piano,p_student,p_status')
            ->find();
        if($pdata['p_status'] != 1){
            return json(['code' => 100, 'msg' => '此课程计划所属课程已下架，不能上架']);
        }
        $res = Db::table('up_plan_info')->where('plan_id', $user_id)->setField('plan_online', 1);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    /**
     * 计划下架
     * @return \think\response\Json
     */
    public function plandown(){
        $user_id = input('id');
        $res = Db::table('up_plan_info')->where('plan_id', $user_id)->setField('plan_online', 2);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    /**
     * 计划删除
     * @return \think\response\Json
     */
    public function plandel(){
        $user_id = input('id');
        $res = Db::table('up_plan_info')->where('plan_id', $user_id)->setField('plan_online', 3);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    //------------------------------------------训练-------------------------------------------------
    //------------------------------------------训练-------------------------------------------------
    //------------------------------------------训练-------------------------------------------------
    /**
     * 训练列表
     * @return mixed|\think\response\Json
     */
    public function practiceinfo(){
        if(request()->isAjax()){
            $p_id = input('p_id');
            $where = [
                'pra_p_id' => $p_id,
                'pra_online' => ['<>',3]
            ];
            $keyword = input('keyword');
            if(isset($keyword) && $keyword != ''){
                $where['pra_name'] = ['like', '%' . $keyword . '%'];
            }
            $NowPage = input('page') ? input('page') : 1;
            $limits = input("limit") ? input("limit") : 10;
            $count = Db::table('up_plan_practice')
                ->where($where)
                ->count();// 获取总条数
            $lists = Db::table('up_plan_practice')
                ->where($where)
                ->page($NowPage,$limits)
                ->order('pra_online asc,pra_date desc,pra_status asc')
                ->select();
            return json(['code' => 220, 'msg' => '', 'count' => $count, 'data' => $lists]);
        }
        $p_id = input('p_id');
        $info = Db::table('up_plan')->alias('p')
            ->join('up_piano pi','p.p_piano=pi.pa_id','LEFT')
            ->join('up_u_user u','p.p_student=u.user_id','LEFT')
            ->where('p_id', $p_id)
            ->field('pa_name,user_username')
            ->find();
        $this->assign([
            'p_id' => $p_id,
            'info' => $info,
        ]);
        return $this->fetch('plan/practiceinfo');
    }
    /**
     * 添加训练
     * @return mixed
     */
    public function addPracticeInfo(){
        $p_id = input('p_id');
        if(Request::instance()->isPost()){
            $pdata = Db::table('up_plan')
                ->where('p_id', $p_id)
                ->field('p_piano,p_student,p_status')
                ->find();
            if(!$pdata || empty($p_id)){
                return json(['code' => 100, 'msg' => '参数有误，请返回重试']);
            }
            if($pdata['p_status'] != 1){
                return json(['code' => 100, 'msg' => '此训练所属课程已下架，不能添加']);
            }
            $today = date('Y-m-d H:i:s');
            $insert = [
                'pra_p_id' => $p_id,
                'pra_name' => input('pra_name'),
                'pra_date' => input('pra_date'),
                'pra_student' => $pdata['p_student'],
                'pra_online' => input('pra_online'),

                'pra_admin' => session('username'),
                'pra_time' => $today
            ];
            $res = Db::table('up_plan_practice')->insert($insert);
            if($res){
                return json(['code' => 200, 'msg' => '成功']);
            }else{
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $this->assign('p_id', $p_id);
        return $this->fetch('plan/addpracticeinfo');
    }
    /**
     * 编辑训练
     * @return mixed
     */
    public function practiceInfoEdit(){
        $pra_id = input('pra_id');
        $info = Db::table('up_plan_practice')->where('pra_id', $pra_id)->find();
        $p_id = $info['pra_p_id'];
        if(Request::instance()->isPost()){
            $today = date('Y-m-d H:i:s');
            $insert = [
                'pra_p_id' => $p_id,
                'pra_name' => input('pra_name'),
                'pra_date' => input('pra_date'),
                'pra_online' => input('pra_online'),

                'pra_admin' => session('username'),
                'pra_time' => $today
            ];
            $res = Db::table('up_plan_practice')->where('pra_id', $pra_id)->update($insert);
            if($res){
                return json(['code' => 200, 'msg' => '成功']);
            }else{
                return json(['code' => 100, 'msg' => '失败']);
            }
        }
        $this->assign('p_id', $p_id);//是弹出层，所以其实不需要
        $this->assign('pra_id', $pra_id);
        $this->assign('info', $info);
        return $this->fetch('plan/editpracticeinfo');
    }
    /**
     * 训练详情
     * @return mixed
     */
    public function practiceinfo_details(){
        $pra_id = input('pra_id');
        $info = Db::table('up_plan_practice')
            ->where('pra_id', $pra_id)
            ->find();
        $info['pra_minus'] = Db::table('up_plan_practice')
            ->where('pra_p_id',$info['pra_p_id'])
            ->where('pra_date',$info['pra_date'])
            ->sum('pra_minus');
        $info['pra_all_minus'] = Db::table('up_plan_practice')
            ->where('pra_p_id',$info['pra_p_id'])
            ->sum('pra_all_minus');
        $info['pra_days'] = Db::table('up_plan_practice')
            ->where('pra_p_id',$info['pra_p_id'])
            ->sum('pra_days');
        $info['pra_times'] = Db::table('up_plan_practice')
            ->where('pra_p_id',$info['pra_p_id'])
            ->sum('pra_times');
        $p_id = $info['pra_p_id'];
        $this->assign('info', $info);
        $p_info = Db::table('up_plan')->alias('p')
            ->join('up_piano pi','p.p_piano=pi.pa_id','LEFT')
            ->join('up_u_user u','p.p_student=u.user_id','LEFT')
            ->where('p_id', $p_id)
            ->field('pa_name,user_username')
            ->find();
        $this->assign('p_info', $p_info);
        return $this->fetch('plan/practiceinfo_detail');
    }
    /**
     * 训练上架
     * @return \think\response\Json
     */
    public function practiceup(){
        $user_id = input('id');
        $p_id = Db::table('up_plan_practice')->where('pra_id', $user_id)->value('pra_p_id');
        $pdata = Db::table('up_plan')
            ->where('p_id', $p_id)
            ->field('p_piano,p_student,p_status')
            ->find();
        if($pdata['p_status'] != 1){
            return json(['code' => 100, 'msg' => '此训练所属课程已下架，不能上架']);
        }
        $res = Db::table('up_plan_practice')->where('pra_id', $user_id)->setField('pra_online', 1);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    /**
     * 训练下架
     * @return \think\response\Json
     */
    public function practicedown(){
        $user_id = input('id');
        $res = Db::table('up_plan_practice')->where('pra_id', $user_id)->setField('pra_online', 2);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
    /**
     * 训练删除
     * @return \think\response\Json
     */
    public function practicedel(){
        $user_id = input('id');
        $res = Db::table('up_plan_practice')->where('pra_id', $user_id)->setField('pra_online', 3);
        if($res){
            return json(['code' => 200, 'msg' => '操作成功']);
        }else{
            return json(['code' => 100, 'msg' => '操作失败']);
        }
    }
}